package com.cloud.bc.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cloud.bc.model.entity.BcConfigs;
import com.cloud.bc.model.entity.BcEmailTemplates;
import com.cloud.bc.model.entity.BcMessageSendRecord;
import com.cloud.bc.service.BcConfigsService;
import com.cloud.bc.service.BcEmailTemplatesService;
import com.cloud.bc.service.BcMessageSendRecordService;
import com.cloud.common.model.entity.EmailTemplates;
import com.cloud.common.model.enums.MailTemplatesEnum;
import com.cloud.common.model.enums.MessageTypeEnum;
import com.cloud.common.model.request.EmailConfig;
import com.cloud.common.util.EmailUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@AllArgsConstructor
@Service
public class BcEmailUtil {
    private final EmailUtil emailUtil;
    private final BcEmailTemplatesService bcEmailTemplatesService;
    private final BcConfigsService bcConfigsService;
    private final BcMessageSendRecordService bcMessageSendRecordService;

    /**
     * 发送邮件
     */
    public boolean sendEmail(MailTemplatesEnum mailTemplatesEnum,
                             String toEmail, JSONObject toValue) {
        //加载邮件模板
        List<BcEmailTemplates> bcEmailTemplates = bcEmailTemplatesService.selectAllCache();
        String bcEmailTemplateStr = JSONUtil.toJsonStr(bcEmailTemplates);
        //加载邮件配置
        List<BcConfigs> bcConfigs = bcConfigsService.selectCacheAll();
        BcConfigs emailConfigModel = bcConfigs.stream().filter(t -> t.getName().equals("EmailConfig")).findFirst().orElse(new BcConfigs());
        EmailConfig emailConfig = JSONUtil.toBean(emailConfigModel.getValue(), EmailConfig.class);
        boolean b = emailUtil.sendMail(emailConfig, bcEmailTemplateStr, mailTemplatesEnum, toEmail, toValue);

        //保存发送记录
        BcMessageSendRecord bcMessageSendRecord = new BcMessageSendRecord();
        bcMessageSendRecord.setSendContent(emailConfig.getSendContent());
        bcMessageSendRecord.setSendType(MessageTypeEnum.EMAIL.getCode());
        bcMessageSendRecord.setSendNo(toEmail);
        bcMessageSendRecordService.save(bcMessageSendRecord);
        return true;
    }
}
